package com.gr.catanddog_web.controller;



import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gr.catanddog_common.aspect.ApiOperationLog;
import com.gr.catanddog_common.damin.*;
import com.gr.catanddog_common.dao.*;
import com.gr.catanddog_common.utils.Response;
import com.gr.catanddog_common.utils.ContentUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
//@RequestMapping("/CatAndDog/")
/*@CrossOrigin(origins ="*",maxAge = 3600,allowCredentials = "true",allowedHeaders = "token")*/
public class ContentController {
    @Autowired
    ContentMapper contentMapper;
    @Autowired
    ContentImageMapper contentImageMapper;
    @Autowired
    SimpleDateFormat formatter;
    @Autowired
    ContentClickMapper contentClickMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserFocusMapper userFocusMapper;
    @Autowired
    CommentMapper commentMapper;
    @Value("${web.url.path}")
    String webPath;
    @Value("${file.upload.url}")
    String filePath;
    /**
     * @description:
     * @author: 大睡大唬
     * @date: 2024/3/3 16:26
     * @param: [token]
     * @return: com.gr.catanddog_common.utils.Response
     **/
    @GetMapping("/gettext")
    @ApiOperationLog(description = "文本文章获取")
    public Response getPassage(Integer value,HttpServletRequest request){
        //String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiLlpKfnnaHlpKfllKwiLCJleHAiOiIxNzA5MDkwOTE5MjI1IiwiaWF0IjoiMTcwOTA5MDkxNTYyNSJ9.CccsWEEzS/cPKatkjCT9+Yl9m5KX2Uf+n3Y2Z/XQFXU=";
        String token = request.getHeader("token");
        String catalogue;
        switch (value){
            case 1:
                catalogue = "故事";break;
            case 2:
                catalogue = "问答";break;
            case 3:
                catalogue = "展示";break;
            default:catalogue = null;
        }
        List<Content> contents = new ArrayList<>();
        LambdaQueryWrapper<Content> lqw1 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> lqw2 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ContentImage> lqw3 = new LambdaQueryWrapper<>();
        if(catalogue!=null)lqw1.eq(Content::getCatalogue,catalogue);
        contents = contentMapper.selectList(lqw1);
        Collections.reverse(contents);
        LambdaQueryWrapper<ContentClick>lqw = new LambdaQueryWrapper<>();
        for (Content content : contents) {
            lqw.clear();lqw2.clear();lqw3.clear();
            lqw.eq(ContentClick::getContentId, content.getId())
                    .eq(ContentClick::getUserToken, content.getUserToken());
            lqw2.eq(User::getToken,content.getUserToken());
            lqw3.eq(ContentImage::getImageId,content.getId());
            ContentClick contentClick = contentClickMapper.selectOne(lqw);
            List<User> user = userMapper.selectList(lqw2);
            content.setUserImg(user.get(0).getHeadPortrait());
            List<ContentImage> contentImages = contentImageMapper.selectList(lqw3);
            List<String>imgurl = new ArrayList<>();
            for (ContentImage contentImage : contentImages) {
                imgurl.add(contentImage.getImageUrl());
            }
            if(contentClick==null){
                content.setIsFocus(false);
                content.setIsUpvote(false);
            }else {
                content.setIsUpvote(contentClick.getIsUpvote());
            }
            content.setImgurl(imgurl);
        }
        return  Response.success(contents);
    }

    @PostMapping("/loadContext")
    @ApiOperationLog(description = "上传文章信息")
    public Response loadPassage(@RequestParam("content") String str,
                                @RequestParam("files")MultipartFile[] files,
                                HttpServletRequest request) throws IOException {
        //String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiLlpKfnnaHlpKfllKwiLCJleHAiOiIxNzA5MDkwOTE5MjI1IiwiaWF0IjoiMTcwOTA5MDkxNTYyNSJ9.CccsWEEzS/cPKatkjCT9+Yl9m5KX2Uf+n3Y2Z/XQFXU=";
        String token = request.getHeader("token");
        Content content = JSON.parseObject(str, Content.class);
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getToken,token));
        content.setCollectNumber(0);
        content.setCommentNumber(0);
        content.setWriter(user.getUserName());
        String time = formatter.format(new Date());
        content.setPubData(time);
        content.setUserToken(token);
        contentMapper.insert(content);
        Content content1 = contentMapper.selectOne(new LambdaQueryWrapper<Content>()
                .eq(Content::getPubData, time)
                .eq(Content::getWriter, content.getWriter()));
        for (MultipartFile file : files) {
            String fileName = String.valueOf(new Date().getTime())+".jpg";
            File dest = new File(filePath+'/'+fileName);
            file.transferTo(dest);
            contentImageMapper.insert(new ContentImage(content1.getId(),webPath+fileName));
        }
        return Response.success();
    }
    @GetMapping("contentRetrve")
    @ApiOperationLog(description = "热门文章推荐")
    public Response contentRetrve(){
        LambdaQueryWrapper<Content> lqw =new LambdaQueryWrapper<>();
        lqw.orderBy(true,false,Content::getLikes)
                .eq(Content::getCatalogue,"问答")
                .last("limit 12");
        List<Content> topic = contentMapper.selectList(lqw);
        lqw.clear();
        lqw.orderBy(true,false,Content::getLikes)
                .eq(Content::getCatalogue,"故事")
                .or()
                .eq(Content::getCatalogue,"展示")
                .last("limit 12");
        List<Content> article = contentMapper.selectList(lqw);
        return Response.success(new ContentUtils(topic,article));
    }
    @GetMapping("/getContent")
    @ApiOperationLog(description = "获取文章详情")
    public Response getContent(@RequestParam("id") String id, HttpServletRequest request){
        //String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiLlpKfnnaHlpKfllKwiLCJleHAiOiIxNzA5MDkwOTE5MjI1IiwiaWF0IjoiMTcwOTA5MDkxNTYyNSJ9.CccsWEEzS/cPKatkjCT9+Yl9m5KX2Uf+n3Y2Z/XQFXU=";
        String token = request.getHeader("token");
        LambdaQueryWrapper<Content>lqw = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> lqw1 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Comment> lqw2 = new LambdaQueryWrapper<>();
        lqw.eq(Content::getId,id);
        Content content = contentMapper.selectOne(lqw);
        lqw1.eq(User::getToken,content.getUserToken());
        User user = userMapper.selectOne(lqw1);
        content.setUserImg(user.getHeadPortrait());
        content.setWriter(user.getUserName());
        lqw2.eq(Comment::getPassageId,content.getId());
        List<Comment> comments = commentMapper.selectList(lqw2);
        for (Comment comment : comments) {
            lqw1.clear();
            lqw1.eq(User::getToken,comment.getUserToken());
            User user1 = userMapper.selectOne(lqw1);
            comment.setUserName(user1.getUserName());
            comment.setImgUrl(user1.getHeadPortrait());
            comment.setUserToken(null);
            comment.setPassageId(null);
        }
        ContentClick contentClick = contentClickMapper.selectOne(new LambdaQueryWrapper<ContentClick>()
                .eq(ContentClick::getContentId, content.getId())
                .eq(ContentClick::getUserToken, token)
        );
        content.setComments(comments);
        if(contentClick!=null){
            content.setIsUpvote(contentClick.getIsUpvote());
            content.setIsCollect(contentClick.getIsCollect());
        }
        return Response.success(content);
    }
    @GetMapping("/comment")
    @ApiOperationLog(description = "添加评论")
    public Response addComment(@RequestParam("id") String id, @RequestParam("text") String text, HttpServletRequest request){
        //String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiLlpKfnnaHlpKfllKwiLCJleHAiOiIxNzA5MDkwOTE5MjI1IiwiaWF0IjoiMTcwOTA5MDkxNTYyNSJ9.CccsWEEzS/cPKatkjCT9+Yl9m5KX2Uf+n3Y2Z/XQFXU=";
        String token = request.getHeader("token");
        LambdaQueryWrapper<Content>lqw = new LambdaQueryWrapper<>();
        lqw.eq(Content::getId,id);
        Content content = contentMapper.selectOne(lqw);
        content.setCommentNumber(content.getCommentNumber()+1);
        contentMapper.update(content,lqw);
        Comment comment = new Comment();
        comment.setUserToken(token);
        comment.setTime(formatter.format(new Date()));
        comment.setText(text);
        comment.setPassageId(id);
        commentMapper.insert(comment);
        return Response.success(comment);
    }
    @GetMapping("upvote")
    @ApiOperationLog(description = "点赞")
    public  Response Upvote(@RequestParam() String id,HttpServletRequest request){
        //String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiLlpKfnnaHlpKfllKwiLCJleHAiOiIxNzA5MDkwOTE5MjI1IiwiaWF0IjoiMTcwOTA5MDkxNTYyNSJ9.CccsWEEzS/cPKatkjCT9+Yl9m5KX2Uf+n3Y2Z/XQFXU=";
        String token = request.getHeader("token");
        LambdaQueryWrapper<Content>lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Content::getId,id);
        Content content = contentMapper.selectOne(lqw1);
        LambdaQueryWrapper<ContentClick> lqw  = new LambdaQueryWrapper<>();
        lqw.eq(ContentClick::getUserToken,token)
                .eq(ContentClick::getContentId,id);
        ContentClick contentClick = contentClickMapper.selectOne(lqw);
        if(contentClick==null){
            contentClick = new ContentClick();
            contentClick.setContentId(id);
            contentClick.setIsUpvote(true);
            content.setLikes(content.getLikes()+1);
            contentMapper.update(content,lqw1);
            contentClick.setIsCollect(false);
            contentClick.setUserToken(token);
            contentClickMapper.insert(contentClick);
        }else{
            if(contentClick.getIsUpvote())content.setLikes(content.getLikes()-1);
            else content.setLikes(content.getLikes()+1);
            contentMapper.update(content,lqw1);
            contentClick.setIsUpvote(!contentClick.getIsUpvote());
            contentClickMapper.update(contentClick, lqw);
        }
        return Response.success();
    }


    @GetMapping("collect")
    @ApiOperationLog(description = "收藏")
    public Response Collect(@RequestParam() String id,HttpServletRequest request){
        //String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiLlpKfnnaHlpKfllKwiLCJleHAiOiIxNzA5MDkwOTE5MjI1IiwiaWF0IjoiMTcwOTA5MDkxNTYyNSJ9.CccsWEEzS/cPKatkjCT9+Yl9m5KX2Uf+n3Y2Z/XQFXU=";
        String token = request.getHeader("token");
        LambdaQueryWrapper<Content>lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Content::getId,id);
        Content content = contentMapper.selectOne(lqw1);
        LambdaQueryWrapper<ContentClick> lqw  = new LambdaQueryWrapper<>();
        lqw.eq(ContentClick::getUserToken,token)
                .eq(ContentClick::getContentId,id);
        ContentClick contentClick = contentClickMapper.selectOne(lqw);
        if(contentClick==null){
            contentClick = new ContentClick();
            contentClick.setContentId(id);
            contentClick.setIsUpvote(false);
            contentClick.setIsCollect(true);
            contentClick.setUserToken(token);
            content.setCollectNumber(content.getCollectNumber()+1);
            contentMapper.update(content,lqw1);
            contentClickMapper.insert(contentClick);
        }else{
            if(contentClick.getIsCollect()){
                content.setCollectNumber(content.getCollectNumber()-1);
            }else content.setCollectNumber(content.getCollectNumber()+1);
            contentClick.setIsCollect(!contentClick.getIsCollect());
            contentMapper.update(content,lqw1);
            contentClickMapper.update(contentClick, lqw);
        }
        return Response.success();
    }
}
